package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/pkg/xlog"
	"github.com/go-pay/gopay/wechat/v3"
	"net/http"
	"time"
	"zhuandan/utils"
	//"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

var (
	mchIdapp                      = "1519557751"
	mchAPIv3Keyapp                = "yewudaoapp1234567891234567891234"
	mchCertificateSerialNumberapp = "65AC5C8464900F2415E2C366FC5D0F99FAA06C88"
	mchPrivateKeyapp              = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFSgKBmqtLkbjl\nLcDCaWz+DkI8sSRnxI1FiB1skI82VFk6D39y9sY9FQ4DY1jlLj6oT7jm/aZrRev9\nZ38PbpTBFDODwT+H8fbgHCcyH4ArGBxtXZp9AM+4u/nhZXZveEnBw76JavOFiyhf\nEeWeO9x/lmNusSxYdBRUt08e6zdBgm2KhE48CHrdAy3KqyeXin0HIDKMN05BASt7\n3APHfpDrBAOuGArfp6L54CeQ/K8ec3MwMC/DZTh8iMtTEY7Vi9bGRa0OAkGoBeSl\noFadlKfRiglISUVsNBTO55BmGdwRRJdT4KLZ4YnTrQnuv50Ym9m4ZRHhqvdgME96\nlHt7/v99AgMBAAECggEANufdALLJ31Mj0OxFzBVJFv9i4b8u8Y4a/vHdtnwYzzb0\nShtMDfOtwgwdBUZd1BJlr7PYMrj+2rXv8mseSm4tCfsURyO+CZiGa2KKagGoStX/\n+1PkjctvA+uUpGz3ZBhm9n0Chv3z3gOXbbXuYHYqbHuvGnxGaiuMCPOnGmS90QX8\nV11xoPQHMviZXizkCibIfUogA0Y3+QL3PzWbQibKdIiPCQeyhabK0/yor+MUW8o8\nwxxdgePkCZhnji466uvmkIA7Gs1cN45Wm3jEmoLR9p4HGpamL2W0Ek60VHvg5oxl\nQJn1S51TsdN8ac/nIq6njORhasRZ+IfUgxAPHTXERQKBgQD/YS1KOWfzWjKXGa+W\nAjhIz3dAVGA7zitmDA5T64uFGuBT7E+WiCd0Ndmt/tdJ119gQ8BqZb4kcnCq0s1n\nN3xufWgYIHe8V94pej9N+mtZwsiQpFr9Jpw8CGjQ52bLSSQDFyuU8eUIWlK9XxtV\nefq+9zMByYx6wPDuByW70uhbTwKBgQDFxLSw6ZPv4bM08uQ1wpbYJ7wSoqZWCsKR\nCdXD2YGn7ejFI6w/qQts+coyCVeDo5gr8dMYE1dbCj4QUtI11Wf3gDnRIJGmlEqf\nOgqOycSeehojwcKtE6QfH3i3uv6dfDeZxG5X1sw302Plb3srYqScNrgAsd8BnQv3\ne1AQVbeVcwKBgBNm25z+/YHEgYFvRyK7anFFqcauYl1IzY1ELzZ696+WGiLmGinS\nkETI7o/Eg7CtdyaGHzE2J5r3Qs4Hk+laks6GIolqtg4OEufNzM9szgkUvk4W3n7L\nFyWMcgIlAm9BUEYX1YzMT90xl4Whmx8EVGN7vllNaanNzMAYtOovHM4LAoGAHfAu\nLk3dwEWZfF18oIrJjQVO2j9XENVmKNClVJWbpBFG2HkS/TwY57FUo4h4gAwG4Dgm\nbZGX+sctKAlxmwaoS3ZUyky039O5DCucJ4txwU/YnysYzlyXzsJT4vRi0PJZ9GQh\nFBkHJzhP+g6LRcEUDDXYWvqSOMtOYXOAZkijlvMCgYEAiJYNQitLJ5NQ86yklF13\nFsEUc6J13rcfbsONutL400ywoDSM1wHcR7f3LkcOmu0cZD+7iXc58ElPYXJpMr9A\n2jnZFD1mE+zJXtxBNhGFv1fJ4ZKbXRI5VMvXeDc2DrXGvl2RyRRJXZuTHns/5MQM\ntFOI/PFRiWvBJqdBHEjqEe4=\n-----END PRIVATE KEY-----"
)

//微信支付
func Wechatpayapp(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	uid := request.Uid
	price := request.Price
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	var buyp models.Buypackage
	data_source.Db.Where("price = ?", price).First(&buyp)
	title := "充值金额：" + utils.FloatToStr64(price)
	var price1 float64
	price1 = price
	if buyp.ID > 0 {
		price1 = price + buyp.Songprice
		title = buyp.Title
	}

	orderno := Generate(time.Time{})

	orderadd := models.Buyorder{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   price1,
		Title:   title,
	}
	data_source.Db.Create(&orderadd)
	money1 := price * 10
	money2 := int(money1 * 10)
	if uid == 10590 {
		money2 = 1
	}

	client, err := wechat.NewClientV3(mchIdapp, mchCertificateSerialNumberapp, mchAPIv3Keyapp, mchPrivateKeyapp)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("appid", appidapp).
		Set("mchid", mchIdapp).
		Set("description", "测试Jsapi支付商品").
		Set("out_trade_no", orderno).
		Set("time_expire", expire).
		Set("notify_url", pturl+"/user/wechatNotifyapp").
		SetBodyMap("amount", func(bm gopay.BodyMap) {
			bm.Set("total", money2).
				Set("currency", "CNY")
		})

	wxRsp, err := client.V3TransactionApp(ctx, bm)
	jsapi, err := client.PaySignOfApp(appidapp, wxRsp.Response.PrepayId)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Print(wxRsp)
	fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    jsapi,
	})
	return
}

func WechatNotifyapp(c *gin.Context) {

	fmt.Println(c.Request)
	notifyReq, err := wechat.V3ParseNotify(c.Request)
	fmt.Println("notifyReq", notifyReq)
	if err != nil {
		xlog.Error(err)
		return
	}
	result, err := notifyReq.DecryptCipherText(mchAPIv3Keyapp)
	fmt.Println("result.TradeState", result.TradeState)
	fmt.Println("result.TradeState", result.OutTradeNo)
	if result.TradeState == "SUCCESS" { // 验证成功
		//fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupay(result.OutTradeNo)
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}
